<?php
/**
 * 订单类.
 * User: chan
 * Date: 2017/9/28 19:24
 */

namespace app\api\logic;

use app\api\BaseModel;
use app\api\controller\Pay;
use app\api\model\OrderGoods as OrderGoodsModel;
use app\api\model\Order as OrderModel;
use think\Exception;
use think\Log;
use think\Loader;
use think\Request;
use think\Controller;
use think\Db;
use app\api\logic\Membership;


class Order extends BaseModel
{
    protected $products;
    protected $uid;//会员ID
    protected $shop;//店铺数据
    protected $m_order;
    protected $snap;//订单快照数据
    protected $goods;

    /**
     * 下单
     */
    public function place()
    {

        Db::startTrans();

        try {
            $this->checkInputData();
            $this->uid = $this->user['id'];
            if (array_key_exists('products', $this->requestData)) {
                //获取商品信息
                $this->products = $this->getProductsByOrder($this->requestData['products']);

                $this->goods = $this->products;
                //获取订单状态
                $this->products = $this->getOrderStatus();
            }

            //获取订单快照
            $orderSnap = $this->snapOrder();
            $status = self::createOrder($orderSnap);
            $status['pass'] = true;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array('message' => $e->getMessage());
        }
        return $status;
    }

    /**
     * 检测发送数据
     */
    public function checkInputData()
    {
        $res = $this->checkData(
            ["type"],
            ["订单类型不能为空"]
        );
        if (array_key_exists('message', $res)) throw new \Exception($res['message']);
        if (!in_array($this->requestData['type'], array(ORDER_TYPE_BOOK, ORDER_TYPE_RESTAURANT, ORDER_TYPE_TAKEAWAY,ORDER_TYPE_MENTION))) throw new \Exception('订单类型错误');
        if (!array_key_exists('shop_id', $this->requestData)) throw new \Exception('店铺ID不能为空');
        $this->getShop(intval($this->requestData['shop_id']));
        switch ($this->requestData['type']) {
            case ORDER_TYPE_BOOK:
                $res = $this->checkData(
                    ["book_time", "total_price","products"],
                    ["预定时间不能为空", "订单总价不能为空","菜品不能为空"]
                );
                if (array_key_exists('message', $res)) throw new \Exception($res['message']);
                break;
            case ORDER_TYPE_TAKEAWAY:
                $res = $this->checkData(
                    ["address","products", "total_price"],
                    ["收货地址不能为空","菜品不能为空", "订单总价不能为空"]
                );
                if (array_key_exists('message', $res)) throw new \Exception($res['message']);
                break;
            case ORDER_TYPE_RESTAURANT:
                $res = $this->checkData(
                    ["products", "total_price"],
                    ["菜品不能为空", "订单总价不能为空"]
                );
                if (array_key_exists('message', $res)) throw new \Exception($res['message']);
                break;
            case ORDER_TYPE_MENTION:
                $res = $this->checkData(
                    ["products", "total_price"],
                    ["菜品不能为空", "订单总价不能为空"]
                );
                if (array_key_exists('message', $res)) throw new \Exception($res['message']);
                break;
        }

    }


    /**
     * 查询店铺
     */
    public function getShop($shopid)
    {
        //满减按总门店来算
        $discount = db('shop')->where(['id' => $shopid])->value('discount');

        $this->shop = db('shop')->where(['id'=>$shopid])->find();
        $this->shop['discount'] = $discount;

        if (!$this->shop) throw new \Exception('找不到店铺');
        if($this->shop['status'] != 1) throw new \Exception('该店铺正在审核中');
        //todo 关店状态
        if ($this->requestData['type'] == ORDER_TYPE_TAKEAWAY) {
            if ($this->shop['issend'] != OUTFOOD_OPEN) throw new \Exception('该店铺并没有开启配送');
        }
        if ($this->requestData['type'] == ORDER_TYPE_BOOK) {
            if ($this->shop['isbook'] != ORDERING_OPEN) throw new \Exception('该店铺并没有开启预约');
        }
    }


    /**
     * 根据订单查询产品
     *
     */
    private function getProductsByOrder($orderProducts)
    {
        foreach($orderProducts as $key=>$value){
            if(!empty($value['goodsid']) && !empty($value['specs'])){
                throw new \Exception('goodsid与specs只能传一个参数');
                break;
            }
        }

        $goodsid = array_column($orderProducts, 'goodsid');
        $specs = array_column($orderProducts, 'specs');

        $goods_specs = db('goods_option')->alias('go')
            ->join('goods g', 'g.id = go.goodsid')
            ->where(['go.id' => array('in', $specs),'g.status'=>'1'])
            ->field('g.*,go.stock as stock,go.id as specs,go.price,go.title')
            ->select();

        $goods_result = db('goods')->where(['id'=>array('in',$goodsid),'status'=>'1'])->select();
		
        foreach($goods_result as &$v){
            $v['specs'] = 0;
            $v['title'] = '';
        }
        if(!empty($specs)){
            if (empty($goods_specs)) {
                throw new \Exception('找不到菜品或者该菜品已下架');
            }
        }
		
        if(!empty($goodsid)){
            if (empty($goods_result)) {
                throw new \Exception('找不到菜品或者该菜品已下架');
            }
        }

        if(empty($specs) && empty($goodsid)){
            throw new \Exception('请添加商品再提交订单!');
        }

        $product_result = array_merge($goods_specs, $goods_result);

        foreach ($product_result as $k=>&$v) {
            if($v['stock'] < $orderProducts[$k]['count']) throw new \Exception($v['name'] . '库存不足，仅剩余'.$v['stock']);
            if(isset($orderProducts[$k]['param'])){
                $v['param']=$orderProducts[$k]['param'];
            }
        }

        return $product_result;
    }

    /**
     * 获取订单状态
     *
     */
    private function getOrderStatus()
    {
        $status = [
            'orderStatus' => true,
            'orderPrice' => 0,
            'goodsStatusArray' => []
        ];

        foreach ($this->requestData['products'] as $orderProduct) {
            if(!empty($orderProduct['specs'])){
                $specs = $orderProduct['specs'];
            }else{
                $specs = $orderProduct['goodsid'];
            }

            $productsStatus = $this->getProductStatus(
                $specs,
                $orderProduct['count'],
                $this->products
            );

            $status['orderPrice'] += $productsStatus['goodsTotalPrice'];
            array_push($status['goodsStatusArray'], $productsStatus);
        }

        return $status['goodsStatusArray'];
    }


    private function getProductStatus($productId, $oCount, $products)
    {
        $productIndex = -1;
        $productStatus = [
            'goods_id' => null,
            'goods_name' => '',
            'count' => 0,
            'goods_price' => 0,
            'goodsTotalPrice' => 0
        ];

        for ($i = 0; $i < count($products); $i++) {
            if(!empty($products[$i]['specs'])){
                $id = $products[$i]['specs'];
            }else{
                $id = $products[$i]['id'];
            }
            if ($productId == $id) {
                $productIndex = $i;
                if ($products[$i]['shop_id'] != $this->shop['id']) {
                    //throw new \Exception($products[$i]['name'] . '不属于该店铺');
                }
                if ($products[$i]['stock'] < 1) {
                    throw new \Exception($products[$i]['name'] . '已售罄');
                }
                if ($products[$i]['status'] == 0) {
                    throw new \Exception($products[$i]['name'] . '已下架');
                }
            }
        }

        if ($productIndex == -1) {
            throw new \Exception('订单创建失败,spec为' . $productId . '的商品不存在');
        } else {
            $product = $products[$productIndex];
            $productStatus['goods_id'] = $products[$productIndex]['id'];
            $productStatus['specs'] = $products[$productIndex]['specs'];

            $productStatus['goods_name'] = $product['name'];
            $productStatus['goods_image'] = $product['image'];
            $productStatus['des'] = $product['des'];
            $productStatus['cid'] = $product['cid'];
            $productStatus['count'] = $oCount;
            $productStatus['goods_price'] = $product['price'];
            $productStatus['goodsTotalPrice'] = $product['price'] * $oCount;
            $productStatus['title'] = $product['title'] != ''?$product['title']:'';
            $productStatus['oldprice'] = $product['oldprice'] != '0.00'?$product['oldprice']:'0.00';
        }
        return $productStatus;
    }

    private function createOrder($snap)
    {

        $products = $this->snap["products"];
        unset($this->snap["products"]);
        db('Order')->insert($this->snap);

        $orderID = db('Order')->getLastInsID();
        $create_time = db('Order')->where(array('order_sn'=>$this->snap['order_sn']))->field('create_time')->find();
		
        if (!empty($products)) {
            foreach ($products as &$pointer) {
                $pointer['order_id'] = $orderID;
            }

            $orderProduct = new OrderGoodsModel();
            $orderProduct->saveAll($products);

//            //删减库存
//            foreach($products as $v){
//                if(!empty($v['spec_id'])){
//                    db('goods_option')->where(['id'=>$v['spec_id']])->setDec('stock',$v['goods_num']);
//                }else{
//                    db('goods')->where(['id'=>$v['goods_id']])->setDec('stock',$v['goods_num']);
//                }
//            }
        }

        return [
            'order_sn' => $this->snap['order_sn'],
            'order_id' => $orderID,
            'create_time' => date('Y-m-d H:i:s',$create_time['create_time'])
        ];
    }

    // 预检测并生成订单快照
    private function snapOrder()
    {
        // status可以单独定义一个类
        $this->snap = [
            'order_sn' => $this->generateOrderNo(),
            'order_ticket' => $this->getfourStr(),
            'total_price' => 0,
            'total_count' => 0,
            'status' => ORDER_STATUS_NOPAY,
            'products' => [],
            'user_id' => intval($this->uid),
            'shop_id' => $this->shop['id'],
            'address' => array_key_exists('address', $this->requestData) ? htmlspecialchars($this->requestData['address']) : '',
            'lng'=>$this->requestData['lng'],
            'lat'=>$this->requestData['lat'],
            'preference' => array_key_exists('preference', $this->requestData) ? htmlspecialchars($this->requestData['preference']) : '',
            'type' => $this->requestData['type'],
            'create_time' => TIMESTAMP,
            'update_time' => TIMESTAMP,
            'send_time'=> TIMESTAMP,
            'driver_id'=>0,
            'route_id'=> 0,
            'route_address_id'=> 0
        ];
        if (array_key_exists('products', $this->requestData)) {
            $this->snap['product_name'] = $this->products[0]['goods_name'];
            $this->snap['product_img'] = $this->products[0]['goods_image'];
            if (count($this->products) > 1) {
                $this->snap['product_name'];
            }
            foreach ($this->products as $k=>$p) {
                if(isset($this->requestData['products'][$k]['param'])){
                    $p['param']=$this->requestData['products'][$k]['param'];
                }
                $pStatus = $this->snapProduct($p);
                $this->snap['total_price'] += $p['goodsTotalPrice'];
                $this->snap['total_count'] += $p['count'];
                array_push($this->snap['products'], $pStatus);
            }
        }
        //属性值
        if(array_key_exists('param', $this->requestData)){
            $param = $this->requestData['param'];
            $this->snap['param'] = $param;
        }

        //满减
        if(!empty($this->shop['discount'])){
            $this->shop['discount'] = unserialize($this->shop['discount']);
			// var_dump($this->shop['discount']);
            foreach($this->shop['discount'] as $key=>$value){
                if($value['full']>$this->snap['total_price'])unset($this->shop['discount'][$key]);
            }
            if($this->shop['discount']) {
                $reduce_array = array_column($this->shop['discount'], 'reduce');
                $full_array = array_column($this->shop['discount'], 'full');
                $this->snap['total_price'] -= max($reduce_array);
                $this->snap['discount_title'] = '满' . max($full_array) . '减' . max($reduce_array) . '元';
                $this->snap['discount'] = max($reduce_array);
            }
        }
        //配送
        if ($this->requestData['type'] == ORDER_TYPE_TAKEAWAY) {
            if($this->shop['send_fee'] != '0.00'){
                $this->snap['total_price'] += $this->shop['send_fee'];
                $this->snap['send_fee'] = $this->shop['send_fee'];
            }

            if(empty($this->user['mobile']) && !isset($this->user['mobile'])) throw new \Exception('绑定手机号才能下单');
        }
        //配送线路与线路地址
        $lng = $this->snap['lng'];
        $lat = $this->snap['lat'];
        if($lng && $lat){
            $route = $this->getMinDistance_Line($this->shop['id'], $lng, $lat);
            if(!empty($route)){
//                $this->snap['driver_id'] = $route['driver_id'];
                $this->snap['route_id'] = $route['route_id'];
                $this->snap['route_address_id'] = $route['id'];
                $this->snap['send_time'] = getSendtime(TIMESTAMP, $route['id']);
            }else{
                throw new \Exception('商家未开通配送');
            }
        }

        $requestData_total_price = strval($this->requestData['total_price']);
        $snap_total_price = strval($this->snap['total_price']);


		// var_dump($snap_total_price);
		// var_dump($requestData_total_price);
        if($snap_total_price != $requestData_total_price) throw new \Exception('订单总价错误');

        //检测是否在开店
        if($this->shop['isopen'] == 0)throw new \Exception('店铺休息中');

        if(!empty($this->shop['open_time']) && $this->shop['open_time'] != ''){
            $time = TIMESTAMP;

            $open_time = unserialize($this->shop['open_time']);
            $bool = false;

            foreach($open_time as $k=>$v){
                $starttime = strtotime($v['starttime']);
                $endtime = strtotime($v['endtime']);

                if ($starttime < $time && $endtime > $time)
                {
                    $bool = true;
                    break;
                }
            }

            if(!$bool){
                throw new \Exception('不在营业时间内');
            }
        }

        if(!isset($this->requestData['preference']))throw new \Exception('请填写备注信息');

        if($this->requestData['type'] == ORDER_TYPE_TAKEAWAY){
            if(empty($this->requestData['delivery_time_start']))throw new \Exception("请先选择配送时间!");
            if(empty($this->requestData['delivery_time_end']))throw new \Exception("请先选择结束时间!");

            $this->snap['delivery_time_start'] = $this->requestData['delivery_time_start'];
            $this->snap['delivery_time_end'] = $this->requestData['delivery_time_end'];
        }

        //送货人名字
        if(!empty($this->requestData['contact_name'])){
            $this->snap['realname'] = $this->requestData['contact_name'];
        }else{
            $this->snap['realname'] = '';
        }

        if(empty($this->requestData['mobile'])){
            $this->snap['mobile'] = $this->user['mobile'];
        }else{
            $this->snap['mobile'] = $this->requestData['mobile'];
        }

        if(!empty($this->requestData['table_id'])){
            $this->snap['table_id'] = $this->requestData['table_id'];
            $db_seat=db("seat");
            $seat=$db_seat->where("id=".$this->requestData['table_id']) ->find();
            $this->snap['table_name']=$seat['name'];
        }else{
            $this->snap['table_id'] = 0;
            $this->snap['table_name']='';
        }
        return $this->snap;
    }

    /**
     * 产品快照
     * @param $product
     * @param $oCount
     * @return array
     */
    private function snapProduct($product)
    {
        $pStatus = array();
        $pStatus['goods_id'] = $product['goods_id'];
        $pStatus['spec_id'] = $product['specs'];
        $pStatus['spec_name'] = $product['title'];
        $pStatus['goods_name'] = $product['goods_name'];
        $pStatus['goods_image'] = $product['goods_image'];
        $pStatus['goods_price'] = $product['goods_price'];
        $pStatus['goods_num'] = $product['count'];
        $pStatus['market_price'] = $product['oldprice'];
        if(isset($product['param'])){
            $pStatus['param'] = $product['param'];
        }
        return $pStatus;
    }

    public static function generateOrderNo()
    {
        $yearCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yearCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 999));
        return $orderSn;
    }

    /**
     * 小票机
     * @param $len
     * @return string
     */
    function getfourStr()
    {
        $mt_rand = mt_rand(1000,9999);

        //今天的时间点
        $new_time = date("Y-m-d");
        $start_time = strtotime("{$new_time} 00:00:00");
        $end_time = strtotime("{$new_time} 23:59:59");

        $where['order_ticket'] = $mt_rand;
        $where['create_time'] = ['>=',$start_time];
        $where['create_time'] = ['<=',$end_time];

        $order = db('order')->where(array('order_ticket'=>$mt_rand))->find();

        if(empty($order))return $mt_rand;

        $this->getfourStr();
    }

    /**
     * 买单
     */
    public function pay()
    {
        if(!isset($this->requestData['order_sn'])){
            return array('message'=>'请传订单号');
        }

        if(!isset($this->requestData['openid'])){
            return array('message'=>'请传微信openid');
        }

        $order_sn = $this->requestData['order_sn'];
        $openid = $this->requestData['openid'];

        $order_result = db('order')->where(array('order_sn'=>$order_sn))->field('id,user_id,total_price,id,shop_id,route_id,route_address_id')->find();
        //是否库存充足
        $products = db('order_goods')->where(['order_id'=>$order_result['id']])->select();
        if (!empty($products)) {
            //库存
            foreach($products as $v){
                if(!empty($v['spec_id'])){
                    $stock = db('goods_option')->where(['id'=>$v['spec_id']])->value('stock');
                }else{
                    $stock = db('goods')->where(['id'=>$v['goods_id']])->value('stock');
                }
                if($stock<$v['goods_num'])return array('message'=>'商品库存不足');
            }
        }
        //修改订单配送时间
       // var_dump($order_result['shop_id']);die;
//        echo '<br/>';
//        var_dump($order_result['route_address_id']);
//        die;
        // $send_time = getSendtime($order_result['shop_id'],$order_result['route_id']);
        $send_time = getSendtime(TIMESTAMP,$order_result['route_id']);
        if($send_time){
            $send_time_data['send_time'] = $send_time;
//            var_dump($send_time_data);die;
            db('order')->where(array('order_sn'=>$order_sn))->update($send_time_data);
        }

        $nickname = db('member')->where(array('id'=>$order_result['user_id']))->field('nickname')->find();
        $nickname = $nickname['nickname'];

        if(empty($order_result)){
            return array('message'=>'非法订单号');
        }

        if($order_result['user_id'] != $this->user['id'])return array('message'=>'该订单不是你的!');

        $order_result['total_price'] = $order_result['total_price']*100;

        $params = array();
        $params["trxamt"] = $order_result['total_price'];
        $params["reqsn"] = $order_sn;//订单号,自行生成
        $params["body"] = $nickname;
        $params["remark"] = "备注信息";
        $params["acct"] = $openid;

        //调取支付接口
        $allinpay =  new \app\api\service\Allinpay();
        $pay_result = $allinpay->pay($params);
		
		if("SUCCESS"==$pay_result["retcode"]){
            if(isset($pay_result['payinfo'])){
                db('sign_success_log')->insert(array('order_sn'=>$order_sn,'pay_log'=>json_encode($pay_result)));
//                /*更新司机配送订单*/
//                $this->upateDriverordInfo($order_result,$send_time);
                return json_decode($pay_result['payinfo'],true);
            }else{
                db('sign_failure_log')->insert(array('order_sn'=>$order_sn,'pay_log'=>json_encode($pay_result)));
                return array("message"=>"支付失败");
            }
		}
    }


    /**
     * 订单列表
     */
    public function index()
    {
        $page=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $limit=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $type=isset($this->requestData['type'])?$this->requestData['type']:'0';
        $where = array();
        if(isset($this->requestData['status'])){
            switch ($this->requestData['status']) {
                case '0':
                    //待付款
                    $where['or.status'] = '0';
                    break;
                case '1':
                    //查询未评价的订单
                    $where['or.iscomment'] = '0';
                    $where['or.status'] = '3';
                    break;
                case '2':
                    //查询已完成的订单
                    $where['or.iscomment'] = '1';
                    $where['or.status'] = '3';
                    break;
                case '3':
                    //查询待发货的订单
                    $where['or.iscomment'] = '0';
                    $where['or.status'] = '1';
                    break;
                case '4':
                    //查询待收货的订单
                    $where['or.iscomment'] = '0';
                    $where['or.status'] = '2';
                    break;
            }
        }else{
            $where['or.status'] =array("neq",'-2');
        }

        if(!empty($type))$where['or.type'] = $type;

        $where['or.user_id'] = $this->user['id'];
        //订单数量
        $count = db('order')->alias('or')
            ->join('shop s','s.id=or.shop_id')
            ->where($where)
            ->count();

        $order = db('order')->alias('or')
            ->join('shop s','s.id=or.shop_id')
            ->field('or.id,or.product_name,or.status,or.create_time,or.pay_time,or.total_price,or.total_price,or.shop_id,s.shopname,s.headimage,or.iscomment')
            ->where($where)
            ->order('or.id desc')
            ->page($page,$limit)
            ->select();
        // ECHO $this->getLastSql();EXIT;
        $order_time_string = config('order_time.expire_in');
        $order_finish = config('order_time.finish');
        foreach($order as $key=>&$value){
            //购买多少件商品
            $goods_count = db('order_goods')->where(['order_id'=>$value['id']])->count();
            $order[$key]['goods_count'] = $goods_count;
            //把过期订单更新完 
            if(TIMESTAMP > ($value['create_time'] + $order_time_string) && $value['status'] == '0'){
                db('order')->where(['id'=>$value['id'],'status'=>'0'])->update(['status'=>'-2']);
                unset($order[$key]);
            }

            $value['headimage'] = IMG_PATH.$value['headimage'];
            $value['create_time'] = date('Y-m-d h:i:s',$value['create_time']);
        }

        return array('list' => array_merge($order), 'page_num' => $page, 'page_limit' => $limit, 'count' => $count);
    }

    /**
     * 自提收货码
     */
    public function code(){
        if(!isset($this->requestData['id']))return array("message"=>"订单id参数有误!");
        $condition['id'] = $this->requestData['id'];
        $order_result = db('order')->where($condition)->find();
        if(empty($order_result))return ["message"=>"订单id参数有误!"];
        if($order_result['user_id'] != $this->user['id'])return ["message"=>"订单id参数有误!"];
        if($order_result['type'] != '4')return ["message"=>"订单id参数有误!"];


        $path =$this->makeWriteCode($this->requestData['id'],$this->user['id']);

        return ['path'=>$path];
    }

    /**
     * 生成核销码
     */
    public function makeWriteCode($order_id,$user_id){
        vendor("phpqrcode.phpqrcode");
        $url= "order_id={$order_id};user_id={$user_id}";
        $errorCorrectionLevel = 'H';//容错级别
        $matrixPointSize = 6;//生成图片大小
        //生成二维码图片
        $this->checkPath(ROOT_PATH.'public\static\code');

        \QRcode::png($url,ROOT_PATH. 'public\static\code\/'.$order_id.'_'.$user_id.'.png', $errorCorrectionLevel, $matrixPointSize, 2);

        return 'static/code/'.$order_id.'_'.$user_id.'.png';
    }

    /**
     *   二维码路径
     */
    public function Wechatcode($order_id,$user_id){
        $result =  new \app\api\logic\Wechatcode();
        $result = $result->get_receipt($order_id,$user_id);
        return $result;
    }

    /**
     * 生成二维码
     */
    public function makeQr($order_id, $user_id){
        //生成二维码图片
        $img_path_binary = $this->Wechatcode($order_id,$user_id);
        $img_name = md5($img_path_binary);

        $this->checkPath('./static/code');

        $file = fopen('./static/code/'.$img_name.".png","w");//打开文件准备写入
        fwrite($file,$img_path_binary);//写入
        fclose($file);//关闭

        return 'code/'.$img_name.".png";
    }

    /**
     * 检查目录是否可写
     * @param  string   $path    目录
     * @return boolean
     */
    protected function checkPath($path)
    {
        if (is_dir($path)) {
            return true;
        }
        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 订单详情
     */
    public function detail()
    {
        $condition['user_id'] = $this->user['id'];
        $condition['o.id'] = $this->requestData['id'];
        $list = db('order')->alias("o")
            ->join("shop s","s.id=o.shop_id")
            ->field("o.type,s.shopname,s.headimage,o.id,o.status,pay_type,order_sn,total_price,discount_title,iscomment,o.create_time,finish_time,pay_time,startsend_time,end_time,send_time,o.shop_id,o.realname,o.mobile,o.address,o.route_id")
            ->where($condition)->find();
        if (empty($list)) return array('message' => '订单不存在');
        $order_time_string = config('order_time.expire_in');
        if(TIMESTAMP <($list['create_time'] + $order_time_string) and $list['status'] == '0'){
            $list['deadtime']=$list['create_time']+$order_time_string-TIMESTAMP;
        }else{
            $list['deadtime']=0;
        }
        $list['take_time'] = '';
        $list['driver'] = [];
        $driver_where['route_id'] = $list['route_id'];
        $driver_where['status'] = 1;
        $driver_where['driver_id'] = ['<>',0];
        $driver_order = db('driver_order')->where($driver_where)->find();
        if(!empty($driver_order)){
            $list['take_time'] = date("Y-m-d H:i:s", $driver_order['take_time']);
            $list['driver'] = db('driver')->where(['id'=>$driver_order['driver_id']])->field('id,nickname,mobile')->find();
        }
        $where['order_id'] = $list['id'];
        $list['order_goods'] = db('order_goods')
            ->field("goods_price,goods_name,goods_num,param,spec_name,goods_image")
            ->where($where)->select();
        if ($list['create_time']) {
            $list['create_time'] = date("Y-m-d H:i:s", $list['create_time']);
        }
        if ($list['finish_time']) {
            $list['finish_time'] = date("Y-m-d H:i:s", $list['finish_time']);
        }
        if ($list['pay_time']) {
            $list['pay_time'] = date("Y-m-d H:i:s", $list['pay_time']);
        }
        if ($list['startsend_time']) {
            $list['startsend_time'] = date("Y-m-d H:i:s", $list['startsend_time']);
        }
        if ($list['end_time']) {
            $list['end_time'] = date("Y-m-d H:i:s", $list['end_time']);
        }
        if ($list['send_time']) {
            $list['send_time'] = date("Y-m-d H:i:s", $list['send_time']);
        }
        if ($list['headimage']) {
            $list['headimage'] =IMG_PATH . $list['headimage'];
        }
        foreach ($list['order_goods'] as &$item) {
            $item['goods_image'] = IMG_PATH . $item['goods_image'];
        }
        return $list;
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $condition['id'] = $this->requestData['id'];
        $condition['user_id'] = $this->user['id'];
        $this->model_order= db('order');
        $list = $this->model_order->where($condition)->find();
        if(!$list) return array('message'=>'订单不存在');
        if ($list['status'] !='0') return array('message' => '非待支付状态，不能取消订单');
        $order_goods = db('order_goods')->where(['order_id' => $list['id']])->select();
        if (empty($order_goods)) return array('message' => '取消订单失败!');
        Db::startTrans();
        try {
            if (!$this->model_order->where(['id' => $list['id']])->update(['status' =>'-2'])) {
                throw new \Exception('取消订单失败');
            }
            $model_goods = db('goods');
            $model_spec = db('goods_option');
            foreach ($order_goods as $g) {
                if($g['spec_id'] > 0){
                    if($model_spec->where(['id' => $g['spec_id']])->setInc('stock',$g['goods_num']) === false){
                        throw new \Exception('返回规格库存失败');
                    }
                }
                if ($model_goods->where(['id' => $g['goods_id']])->setInc('stock', $g['goods_num']) === false){
                    throw new \Exception('返回库存失败');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array('message' => $e->getMessage());
        }
        return array();
    }


    /**
     * 评论订单
     */
    public function comment()
    {
        $condition['id'] = $this->requestData['id'];
        $condition['user_id'] = $this->user['id'];
        if(!isset($this->requestData['content']) && empty($this->requestData['content'])){
            return array('message' => '评论内容不能为空');
        }
        $this->model_order= db('order');
        $list = $this->model_order->where($condition)->find();
        if(!$list) return array('message'=>'订单不存在');
        if ($list['status'] !='3') return array('message' => '非待评论状态');
        if ($list['iscomment'] !='0') return array('message' => '已评论');
        if($list['driver_id']){
            $driver['driver_content'] = $this->requestData['driver_content'];
            $driver['driver_grade'] = $this->requestData['driver_grade'];
            if(empty($driver['driver_content']) || empty($driver['driver_grade']))return ['message'=>'请对司机进行评价'];
            $grade = $driver['driver_grade'];
            if(!in_array($grade,[1,2,3,4,5]))['message'=>'请对司机进行评分'];
            db('driver_order_comment')->insert($driver);
        }


        $db_comment = db('comment');

        $data=array(
            "uid"=> $this->user['id'],
            "shop_id"=>$list['shop_id'],
            "content"=>$this->requestData['content'],
            "create_time"=>TIMESTAMP
        );
        $db_comment->insert($data);
        $comment_id = db('comment')->getLastInsID();

        Db::startTrans();
        try {
            if (!$this->model_order->where(['id' => $list['id']])->update(['iscomment' =>'1'])) {
                throw new \Exception('更改评论状态失败');
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array('message' => $e->getMessage());
        }

        return array('comment_id'=>$comment_id);
    }


    public function uptade_comment_img(){
        $comment_id = $this->requestData['comment_id'];
        if(empty($comment_id)) return array('message' => '评论id为空');
        $comment_result = db('comment')->where(['id'=>$comment_id])->find();
        if(empty($comment_result)) return array('message' => 'id为非法id');

        $images = [];
        if(!empty($comment_result['images']) and $comment_result['images'] != ''){
            $images = unserialize($comment_result['images']);
        }

        $files = request()->file('image');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($files){
            $info = $files->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $images[]=$info->getSaveName();
            }else{
                return array('message' => $info->getError());
            }
        }

        if(!empty($images)){
            $update_images = serialize($images);

            $bool = db('comment')->where(['id'=>$comment_id])->update(['images'=>$update_images]);
            if(!$bool)return array('message' => '更新失败！');
        }else{
            return array('message' => '更新失败！');
        }
    }


    /**
     * 确认收货
     */
    public function receive()
    {
        $condition['id'] = $this->requestData['id'];
        if(!isset($this->requestData['user_id'])){
            $condition['user_id'] = $this->user['id'];
        }else{
            $condition['user_id'] = $this->requestData['user_id'];
        }

        $this->model_order= db('order');
        $order = $this->model_order->where($condition)->find();
        if(!$order) return array('message'=>'订单不存在');
        if ($order['status'] != '1' && $order['status'] != '2') return array('message' => '非待完成状态');
        Db::startTrans();
        try {
            $orderdata = [
                'status' => 3,
                'finish_time' => TIMESTAMP
            ];
            $res=$this->model_order->where(['id' => $order['id']])->update($orderdata);
            if(!$res)  throw new \Exception('确认完成失败');

            //查询平台回扣率
            $system_balance = db('config')->where(['id'=>'7'])->value('value');

            if(!empty($system_balance)){
                //平台回扣
                $system_balance_money = $order['total_price']*($system_balance/100);
                $system_balance_money = substr(sprintf("%.3f",$system_balance_money),0,-1);
                $order['total_price'] = $order['total_price'] - $system_balance_money;

                $system_data['order_id'] = $order['id'];
                $system_data['system_rule'] = $system_balance;
                $system_data['money'] = $system_balance_money;
                //平台记录
                db('system_balance')->insert($system_data);
            }


            //上一级会员获得佣金
            $parent_id = db('membership')->where(['uid'=>$order['user_id']])->value('parent_id');

            if(!empty($parent_id)){
                //会员佣金
                $commission = db('shop')->where(['id'=>$order['shop_id']])->value('commission');

                if(empty($commission)){
                    $system_commission = db('config')->where(['id'=>'6'])->value('value');
                    //平台统一设置回扣
                    $system_commission_money = $order['total_price'] * ($system_commission/100);
                    $system_commission_money = substr(sprintf("%.3f",$system_commission_money),0,-1);
                    $order['total_price'] = $order['total_price'] - $system_commission_money;
                    $member_balance = $system_commission_money;
                    $member_commission = $system_commission;
                }else{
                    //会员回扣
                    $system_commission_money = $order['total_price'] * ($commission/100);
                    $system_commission_money = substr(sprintf("%.3f",$system_commission_money),0,-1);
                    $order['total_price'] = $order['total_price'] - $system_commission_money;
                    $member_balance = $system_commission_money;
                    $member_commission = $commission;
                }

                if(!empty($member_commission)){
                    $member_balance_data['uid'] = $parent_id;
                    $member_balance_data['shop_id'] = $order['shop_id'];
                    $member_balance_data['money'] = $member_balance;
                    $member_balance_data['order_id'] = $order['id'];
                    $member_balance_data['commission_record'] = $member_commission;

                    db('member_balance')->insert($member_balance_data);
                }
            }

            $where_mention_balance['order_id'] = $order['id'];
            $mention_balance = db('mention_balance')->where($where_mention_balance)->find();
            if($mention_balance['status'] == '0' && !empty($mention_balance['id'])){
                if(!empty($mention_balance['money'])){
                    db('mention_balance')->where($where_mention_balance)->update(['status'=>'1']);
                }else{
                    $mention_balance['money'] = 0;
                }
            }else{
                $mention_balance['money'] = 0;
            }

            //固定死某个商户运营
            $shop_id = config('shop.id');
            if($order['shop_id'] != $shop_id){
                $order_shop_id = $shop_id;
            }else{
                $order_shop_id = $order['shop_id'];
            }

            if($order['shop_id'] == $shop_id) {
                $data['order_id'] = $order['id'];
                $data['shop_id'] = $order['shop_id'];
                $data['money'] = $order['total_price'];
                if (!empty($mention_balance['money'])) {
                    $data['mention_money'] = $mention_balance['money'];
                }
                $data['creatime'] = time();
                db('order_stream')->insert($data);
            }else{
                $data['order_id'] = $order['id'];
                $data['shop_id'] = $shop_id;
                $data['money'] = $order['total_price'];
                $data['mention_money'] = 0;
                $data['creatime'] = time();
                db('order_stream')->insert($data);

                $data['shop_id'] = $order['shop_id'];
                $data['money'] = 0;
                $data['mention_money'] = $mention_balance['money'];
                db('order_stream')->insert($data);
            }

            $res2=db("shop")->where(['id'=>$order_shop_id])->setInc("balance",$order['total_price']);

            if(!empty($mention_balance['money'])){
                db("shop")->where(['id'=>$order['shop_id']])->setInc("balance",$mention_balance['money']);
            }

            if(!$res2)  throw new \Exception('商户增加余额失败');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array('message' => $e->getMessage());
        }
        return array();
    }

    /*
	 * 获取配送地址的最优路线信息
	 *
	 */
    public function getMinDistance_Line($shopid,$lng1,$lat1)
    {
        $route_id = db('route')->where(['shop_id'=>$shopid])->column('id');
        if($route_id){
            $data = db('route_address')->where('route_id','in',$route_id)->select();
            if(!empty($data)){
                foreach($data as $key=>&$value){
                    $lat2 = $value['lat'];
                    $lng2 = $value['lng'];
                    $distance  = getDistance($lat1,$lng1,$lat2,$lng2);
                    if(empty($distance)){$value['distance'] = $distance;}else{$value['distance'] = 0;}
                    $juli[$key] = $distance;
                }
                if(!empty($juli)){
                    array_multisort($juli,SORT_ASC,SORT_NUMERIC, $data);
                    return $data[0];
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

}